<template>
  <div>
    <el-form
      class="login-form"
      ref="login-form"
      :model="user"
      :rules="formRules"
    >
      <h1 class="login-logo">注册后台账号</h1>
      <el-form-item prop="mobile">
        <el-input
          v-model="user.mobile"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="user.password"
          type="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password1">
        <el-input
          v-model="user.password1"
          type="password"
          placeholder="请再次输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="code"
        style="display:flex; justify-content: space-between; "
      >
        <el-input
          style="width:162px"
          v-model="user.code"
          placeholder="请输入验证码"
        ></el-input>
        <div
          class="getCode "
          :class="typeof getCodeName === 'string'?'':'isGetCode'"
          @click="varifyMobile"
        >{{getCodeName}}</div>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox v-model="user.agree">我已阅读并同意用户协议和隐私政策</el-checkbox>
      </el-form-item>
      <el-form-item style="position: relative">
        <el-button
          type="primary"
          class="login-btn"
          :loading="loginLoading"
          @click="registerAccount"
        >确认注册</el-button>
      </el-form-item>
      <el-form-item class="noCountStyle">
        已有帐号？ <span @click="loginPage">点此登录</span>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { register, getVerificationCode } from '@/api/user' // loginExtra
import Cookies from 'js-cookie'
import jwt from 'jsonwebtoken'
export default {
  data () {
    const validatePass1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
        // password 是表单上绑定的字段
      } else if (value !== this.user.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      getCodeName: '获取验证码',
      timer: null,
      loginLoading: false,
      user: {
        mobile: '', // 用于获取验证码
        password: '',
        password1: '', // 确认密码
        code: '',
        agree: false
      },
      formRules: {
        // 验证规则
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'change' },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          {
            pattern: /^\d{6}$/,
            message: '密码长度为6位数字',
            trigger: 'change'
          }
        ],
        password1: [
          { required: true, validator: validatePass1, trigger: 'change' },
          {
            pattern: /^\d{6}$/,
            message: '密码长度为6位数字',
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'change' },
          {
            // pattern: /^\d{6}$/,
            message: '验证码长度为6位数字',
            trigger: 'change'
          }
        ],
        agree: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback()
              }
              callback(new Error('请勾选用户协议'))
            },
            // message: '手机号不能为空',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    varifyMobile () {
      // mobile1换成你想监听的prop字段
      this.$refs['login-form'].validateField('mobile', valid => {
        if (valid) {
          return
        }
        // 调用登录接口
        this.getCode()
      })
    },
    getCode () {
      if (this.getCodeName === '获取验证码') {
        this.getCodeName = 60
        getVerificationCode({
          phone: this.user.mobile,
          register: true
        }).then(
          res => {
            // console.log(res)
          },
          res => {
            this.getCodeName = '获取验证码'
            clearInterval(this.timer)
            // console.log(res)
          }
        )
        this.timer = setInterval(() => {
          if (this.getCodeName <= 0) {
            this.getCodeName = '获取验证码'
            clearInterval(this.timer)
          } else {
            this.getCodeName--
          }
        }, 1000)
      }
    },
    registerAccount () {
      if (!Cookies.get('SESSION')) {
        this.getJson()
      }
      // 表单校验规则验证
      this.$refs['login-form'].validate((valid, err) => {
        if (!valid) {
          return
        }
        // 注册
        this.register()
      })
    },
    setSecret () {
      let obj = null
      const { mobile, password, code } = this.user
      obj = { mobile, password, code }
      obj.password = jwt.sign(obj.password, 'luo')
      const token = jwt.sign(obj, 'lmb') // 加密算法
      return Cookies.get('SESSION') + token // session可能获取不到需要做判断
    },
    register () {
      this.loginLoading = true
      // 发送请求
      const token = this.setSecret()
      register(token).then(
        res => {
          setTimeout(() => {
            this.loginLoading = false
            this.$message({
              message: '注册成功',
              type: 'success'
            })
            this.loginPage()
          }, 300)
        },
        err => {
          console.log('注册失败', err)
          this.loginLoading = false
          this.$message({
            message: '注册失败',
            type: 'success'
          })
        }
      )
    },
    loginPage () {
      this.$emit('changeState', 'login')
    }
  }
}
</script>

<style lang='less' scoped>
.login-logo {
  width: 300px;
  font-size: 18px;
  text-align: center;
  color: #333;
  margin-bottom: 22px;
}
.getCode {
  width: 120px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  display: inline-block;
  background: #409eff;
  color: #fff;
  border-radius: 3px;
  margin-left: 18px;
  cursor: pointer;
  border-radius: 10px;
}
.isGetCode {
  opacity: 0.65;
}
.active {
  font-weight: bolder;
}
.login-form {
  background-color: #fff;
  padding: 30px 80px 5px;
  min-width: 300px;
  .login-btn {
    width: 50%;
    position: absolute;
    border-radius: 40px;
    left: 50%;
    transform: translateX(-50%);
  }
}
.noCountStyle {
  margin-top: 60px;
  border-top: 1px solid #e4e7ec;
  text-align: center;
  padding-top: 10px;
  color: #333;
  span {
    color: #409eff;
    cursor: pointer;
  }
}
</style>
